package com.xxl.job.executor.service;

import com.xxl.job.core.log.XxlJobLogger;
import com.xxl.job.executor.kafka.KafkaProduceService;
import com.xxl.job.executor.model.CurrentInfoDhModel;
import com.xxl.job.executor.model.CurrentInfoRqModel;
import com.xxl.job.executor.model.SignalDefRqModel;
import com.xxl.job.executor.repository.CurrentInfoRepository;
import com.xxl.job.executor.utils.ThreadLocalDateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;


/**
 * 文件描述
 *
 * @author wang.kunlin
 * @date 2020年09月15日 16:56
 */
@Service
public class InvadesService {

    private static final Logger LOGGER = LoggerFactory.getLogger(InvadesService.class);
    @Autowired
    private SignalDefService signalDefService;
    @Autowired
    private CurrentInfoRepository currentInfoRepository;
    @Autowired
    private KafkaProduceService kafkaProduceService;

    @Autowired
    private BkJsonDataService bkJsonDataService;


    /**
     * SignalType 03
     *
     * @author wang.kunlin
     * @date 2020年08月19日 16:56
     */
    public void save(SignalDefRqModel automaticControlModel, int flag) {

        List<SignalDefRqModel> queryRqSignalList = signalDefService.queryRqSignalList(
                automaticControlModel.getGatherId(), automaticControlModel.getGatherResId(), automaticControlModel.getSignalType(), automaticControlModel.getPointAddr());
        if (queryRqSignalList == null) {
            // LOGGER.error("自控系统：未找到对应的信号配置");
            return;
        } else {
            for (int num = 0; num < queryRqSignalList.size(); num++) {
                String nDate = "";
                nDate = ThreadLocalDateUtil.formatDate(new Date());

                // String signalType  =queryRqSignalList.get(num).getSignalType();

                //新建实时存储的实体
                CurrentInfoRqModel currentInfoRqModel = new CurrentInfoRqModel();

                currentInfoRqModel.setValue(automaticControlModel.getSignalValue());
                currentInfoRqModel.setGatherResId(automaticControlModel.getGatherResId());
                currentInfoRqModel.setGatherId(automaticControlModel.getGatherId());
                currentInfoRqModel.setDevCode(queryRqSignalList.get(num).getDevCode());
                currentInfoRqModel.setSignalCode(queryRqSignalList.get(num).getCode());
                currentInfoRqModel.setSignalName(queryRqSignalList.get(num).getName());
                currentInfoRqModel.setSignalType(queryRqSignalList.get(num).getSignalType());
                currentInfoRqModel.setValunit(queryRqSignalList.get(num).getValunit());
                currentInfoRqModel.setTime(nDate);
                currentInfoRqModel.setPointAddr(queryRqSignalList.get(num).getPointAddr());

                //根据实体去redis查询上次信号时间
                CurrentInfoRqModel currentInfoRqModel1 = currentInfoRepository.queryRqCurrent(queryRqSignalList.get(num).getDevCode(), queryRqSignalList.get(num).getCode());

                if (currentInfoRqModel1 == null) {
                    currentInfoRqModel.setLastTime(nDate);
                } else {
                    currentInfoRqModel.setLastTime(currentInfoRqModel1.getTime());
                }
                currentInfoRqModel.setSendTime(ThreadLocalDateUtil.formatDate(new Date()));
                //  System.out.println(currentInfoRqModel.getPointAddr()+": "+currentInfoRqModel.getValue());
                boolean isSend = this.isSaveRedis(currentInfoRqModel, currentInfoRqModel1, flag);
                if (isSend){
                    //实时数据存入redis
                    currentInfoRepository.save(currentInfoRqModel);

                    //发送kafka
                    sends(currentInfoRqModel);


                    //发送博坤
                    bkJsonDataService.sendDevInfoMessage(queryRqSignalList.get(num).getCode(),
                            queryRqSignalList.get(num).getName(),
                            queryRqSignalList.get(num).getSignalType(),
                            queryRqSignalList.get(num).getDevCode(),
                            automaticControlModel.getSignalValue(),
                            queryRqSignalList.get(num).getValunit(),
                            nDate);
                }

            }


        }


    }

    /**
     * SignalType 01 、02
     *
     * @author wang.kunlin
     * @date 2020年08月19日 16:56
     */

    public void saves(SignalDefRqModel automaticControlModel, int flag) {
        SignalDefRqModel signalDefRqModel = signalDefService.queryRqSignal(
                automaticControlModel.getGatherId(), automaticControlModel.getGatherResId(), automaticControlModel.getSignalType(), automaticControlModel.getPointAddr());
        if (signalDefRqModel == null) {
            // LOGGER.error("自控系统：未找到对应的信号配置");
            return;
        }
        String nDate = "";
        nDate = ThreadLocalDateUtil.formatDate(new Date());

        String signalType = signalDefRqModel.getSignalType();

        //新建实时存储的实体
        CurrentInfoRqModel currentInfoRqModel = new CurrentInfoRqModel();

        currentInfoRqModel.setValue(automaticControlModel.getSignalValue());
        currentInfoRqModel.setGatherResId(automaticControlModel.getGatherResId());
        currentInfoRqModel.setGatherId(automaticControlModel.getGatherId());
        currentInfoRqModel.setDevCode(signalDefRqModel.getDevCode());
        currentInfoRqModel.setSignalCode(signalDefRqModel.getCode());
        currentInfoRqModel.setSignalName(signalDefRqModel.getName());
        currentInfoRqModel.setSignalType(signalDefRqModel.getSignalType());
        currentInfoRqModel.setValunit(signalDefRqModel.getValunit());
        currentInfoRqModel.setTime(nDate);
        currentInfoRqModel.setPointAddr(signalDefRqModel.getPointAddr());

        //根据实体去redis查询上次信号时间
        CurrentInfoRqModel currentInfoRqModel1 = currentInfoRepository.queryRqCurrent(signalDefRqModel.getDevCode(), signalDefRqModel.getCode());

        if (currentInfoRqModel1 == null) {
            currentInfoRqModel.setLastTime(nDate);
        } else {
            currentInfoRqModel.setLastTime(currentInfoRqModel1.getTime());
        }
        currentInfoRqModel.setSendTime(ThreadLocalDateUtil.formatDate(new Date()));
        //实时数据存入redis
        boolean isSend = this.isSaveRedis(currentInfoRqModel, currentInfoRqModel1, flag);
        if (isSend){
            currentInfoRepository.save(currentInfoRqModel);
            //发送kafka
            sends(currentInfoRqModel);


            //发送博坤
            bkJsonDataService.sendDevInfoMessage(signalDefRqModel.getCode(),
                    signalDefRqModel.getName(),
                    signalDefRqModel.getSignalType(),
                    signalDefRqModel.getDevCode(),
                    automaticControlModel.getSignalValue(),
                    signalDefRqModel.getValunit(),
                    nDate);
        }



    }


    /**
     * 发kafka
     *
     * @param message
     */
    public void sends(CurrentInfoRqModel message) {

        try {
            this.kafkaProduceService.sendRqAlarmMessage(message);

        } catch (Exception e) {
            XxlJobLogger.log("发送告警信息失败:" + message.toString(), e);
        }
    }


    /**
     * 判断实时数据是否需要存入redis
     *
     * @param automaticControlStatus
     * @param automaticControlStatus1
     * @param flag
     * @return
     */
    private boolean isSaveRedis(CurrentInfoRqModel automaticControlStatus,
                                CurrentInfoRqModel automaticControlStatus1, int flag) {
            int fa = 0;
            long iTimeDiffHour=0;
            String autoVal=automaticControlStatus.getValue();
            String oldautoVal=automaticControlStatus1.getValue();
            if(automaticControlStatus1 != null){
                if(!autoVal.equals(oldautoVal)){
                    fa = 1;
                }
                iTimeDiffHour = (ThreadLocalDateUtil.parse(automaticControlStatus.getTime()).getTime() - ThreadLocalDateUtil.parse(automaticControlStatus1.getTime()).getTime()) / (1000 * 60* 20);
            }else{
                iTimeDiffHour = 2;
            }

            if ( fa > 0 || iTimeDiffHour > 1 || autoVal == "1") {
                return true;
            }
            return false;
        }

}

